'use strict';

const Controller = require('egg').Controller;
const { Sequelize, Op } = require("sequelize");

class BookshelfController extends Controller {
    async setStatus(params) {
        const { model } = this.app
        const { type, status, userId, novelId } = params

        let sql = {
            where: {
                user_id: userId,
                novel_id: novelId
            },
            defaults: {
                user_id: userId,
                type,
                status,
                novel_id: novelId,
                create_time: (new Date).getTime() / 1000,
                update_time: (new Date).getTime() / 1000
            }
        }
        
        let result = await model.Bookshelf.findOrCreate(sql)
        // 已存在
        if (!result[1]) {
            let updateSql = {
                type,
                status
            }
            // 状态和类型一致
            if (type == result[0].type && status == result[0].status) throw {code: '02', msg: '已经存在'}

            result = await model.Bookshelf.update(updateSql, {
                where: {
                    user_id: userId,
                    novel_id: novelId
                }
            });
        }

        return result
    }

    async getNoverList(params) {
        const {model} = this.app
        const { type, status, userId, page, num } = params
        let sql = {}, whereSql = {}

        whereSql = {
            user_id: userId,
            type,
            status
        }
        sql = {
            where: whereSql,
            include: [{
                model: model.Novel,
            }],
            attributes: {
                include: [
                    [Sequelize.literal(`(SELECT score FROM novel_discuss WHERE novel_discuss.novel_id = bookshelf.novel_id AND novel_discuss.user_id = bookshelf.user_id AND novel_discuss.score IS NOT NULL)`), 'score'],
                ]
            },
            limit: num*1, // 返回数据量
            offset: num*(page-1), // 数据偏移量
        }
        const { count, rows } = await model.Bookshelf.findAndCountAll(sql);
        const pageAll = Math.ceil(count/num)

        return {
            page: page,
            pageAll: pageAll,
            data: rows
        }
    }

    async getNoverStatus(params) {
        const {model} = this.app
        const {userId, novelId} = params
        const sql = {
            where: {
                user_id: userId,
                novel_id: novelId
            }
        }
        return await model.Bookshelf.findOne(sql);
    }
}

module.exports = BookshelfController;
